//获取fileID的“绝对路径”
//返回值是parentID

#include "../include/server.h"

int getPath(char *filePath, int fileID, int ownerID){
    //===========所需变量============
    int parentID = 0;
    
    //先连接数据库
    
    MYSQL *conn;
    char *server = "localhost";
    char *user = "root";
    char *password = "1234";
    char *database = "netdisk";//要访问的数据库名称

    //初始化
    conn = mysql_init(NULL);
    if(!conn)
    {
        printf("MySQL init failed\n");
        return -1;
    }

    //连接数据库，看连接是否成功，只有成功才能进行后面的操作
    if(!mysql_real_connect(conn, server, user, password, database, 0, NULL, 0))
    {
        printf("Error connecting to database: %s\n", mysql_error(conn));
        return -1;
    }
    else
    {
        /* printf("MySQL Connected...\n"); */
    }

    do{
        parentID = getParent(conn, filePath, fileID, ownerID);
        fileID = parentID;
        /* printf("parentID = %d\n", parentID); */
    }while(parentID != 0);

    /* printf("filePath = %s\n", filePath); */

    return 1;
}

int getParent(MYSQL *conn, char *filePath, int fileID, int ownerID){
    //如果就在根目录，直接返回
    if(fileID == 0){
        char buf[128] = {0};
        memcpy(buf, filePath, strlen(filePath));
        sprintf(filePath, "/%s", buf);
        return 0;
    }
    //查询数据库，返回文件的parent_id，同时拼接路径path

    //1、拼接查询语句
    char query[300] = "select parent_id,filename from file where id=";
    unsigned int queryRet;
    //将搜索语句拼接起来
    sprintf(query, "%s%d and owner_id=%d", query, fileID, ownerID);

    //在输出前先打印查询语句
    /* puts(query); */
    
    //===========所需变量============
    MYSQL_RES *res;
    MYSQL_ROW row;
    int parentID = 0;
    char fileName[20] = {0};

    //2、查询，拼接path，返回parentID
    queryRet = mysql_query(conn, query);
    if(queryRet){
        printf("Error making query: %s\n", mysql_error(conn));
    }
    else{
        //用mysql_num_rows可以得到查询的结果集有几行
        //要配合mysql_store_result使用
        //第一种判断方式
        res = mysql_store_result(conn);
        /* printf("mysql_num_rows = %lu\n", (unsigned long)mysql_num_rows(res)); */

        //第二种判断方式,两种方式不能一起使用
		/* res = mysql_use_result(conn); */
            
        row = mysql_fetch_row(res);
		if(NULL == row)
        {
            //如果传入的文件名不在file表中，返回0
            printf("Don't find any data\n");
            parentID = -1;
        }
        else{
            //查询成功，获取
            parentID = atoi(row[queryRet++]);
            char buf[64] = {0};
            memcpy(buf, filePath, strlen(filePath));
            memcpy(fileName, row[queryRet], sizeof(fileName));
            /* printf("fileName = %s\n", fileName); */
            sprintf(filePath, "/%s%s", fileName, buf);
        }

    }
    return parentID;
}
